package com.lincoln.bean;

import com.alibaba.dubbo.common.utils.IOUtils;
import com.lincoln.entity.user.DbUser;
import com.lincoln.repository.UserRepository;
import com.lincoln.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class BaseApi {
    /**
     * 检查是否登录
     */
    public static void checkLogin() throws ApiCodeException {
        try {
            long userId = getUserId();
            if (userId <= 0) {
                throw new ApiCodeException(ApiCode.NEED_LOGIN);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public static ServletRequestAttributes getServletRequestAttributes() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        return getServletRequestAttributes().getRequest();
    }

    /**
     * 获取response
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        return getServletRequestAttributes().getResponse();
    }

    /**
     * 获取当前请求绑定的用户id,默认返回0
     *
     * @return
     */
    public static long getUserId() {
        try {
            return Long.parseLong((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取当前请求绑定的用户,默认返回null
     *
     * @return
     */
    public static DbUser getUser() {
        UserService userService = (UserService) SpringBeanFactoryUtils.getBeanByClass(UserService.class);
        return userService.findById(getUserId());
    }

    /**
     * 获取当前请求绑定的APPid,默认返回0
     *
     * @return
     */
    public static long getAppId() {
        // TODO: 2018/6/14 实现
        return 0;
    }

    /**
     * 获取当前请求绑定的用户,默认返回null
     *
     * @return
     */
//    public static App getApp() {
//        // TODO: 2018/6/14 实现
//        return null;
//    }

    /**
     * 获取当前请求的请求体
     *
     * @return
     */
    public static String getBody() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(getRequest().getInputStream()));
            String body = IOUtils.read(reader);
            return body;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 为multipart/form-data类型的请求体切割参数
     *
     * @return
     */
    public static Map<String, List<String>> cutFormDataBody(String body) {
        if (body == null || "".equals(body)) {
            return new HashMap<>();
        }
        String[] strs = body.split("Content-Disposition: form-data; name=\"");
        Map<String, List<String>> result = new HashMap<>();
        if (strs == null || strs.length <= 0) {
            return new HashMap<>();
        }
        for (String str : strs) {
            try {
                String key = str.substring(0, str.indexOf("\"\r\n\r\n"));
                str = str.substring(key.length() + "\"\r\n\r\n".length());
                String value = str.substring(0, str.indexOf("\r\n"));
                List<String> v = new LinkedList<>();
                v.add(value);
                result.put(key, v);
            } catch (Exception e) {
                continue;
            }
        }
        return result;
    }

    /**
     * 获取当前请求的用户的所有权限
     *
     * @return
     */
    public static Collection<? extends GrantedAuthority> getAuthorities() {
        return getAuthentication().getAuthorities();
    }

    /**
     * 获取当前请求的用户的权限
     *
     * @return
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
